const mongoose = require("mongoose")
const bean = require("../bean/files")
const Model = mongoose.model('files', bean)
const HttpException = require("../utils/HttpException")
const {FAILED} = require("../enumeration/code")
const {uuid} = require("../utils")
const fs = require("fs")
const conf = require("../conf/web")
const path = require("path")
module.exports = {
  async save(ctx) {
    let files = ctx.request.files
    if (!files) {
      throw new HttpException("上传文件错误", FAILED, FAILED)
    }

    if (!checkTypes(files.file.type)) {
      try {
        fs.unlinkSync(files.file.path)
      } catch (e) {
      }
      throw new HttpException("文件类型必须是'image/png', 'image/gif', 'image/jpge', 'image/svg+xml", FAILED, FAILED)
    }

    let data = {
      id: uuid(32),
      path: path.resolve(conf.uploadDir, path.basename(files.file.path))
    }

    let model = new Model(data)
    await model.save().catch(e => {
      throw new HttpException(e.message)
    })
    return {
      id: data.id,
      url: `${ctx.origin}${data.path}`
    }

  },
  async find(ctx) {
    let s = await Model.find({})
      .catch(e => {
        throw new HttpException(e.message)
      })
    s.forEach((item, index) => {
      s[index] = {
        path: `${ctx.origin}${item.path}`,
        id: item.id
      }
    })
    return s
  },
  async delete(ctx) {
    let body = ctx.request.body
    let find = await Model.findOne({id: body.id})
    if (!find) return
    let res = await Model.deleteOne({id: body.id})
      .catch(e => {
        throw new HttpException(e.message, FAILED)
      })
    if (res.deletedCount === 0) return false
    try {
      let fpath = path.join( conf.publicPath, find.path)
      fs.unlinkSync(fpath)
      return res
    } catch (e) {
      return false
    }
  }
}

function checkTypes(type) {
  let types = ['image/png', 'image/gif', 'image/jpeg', 'image/svg+xml']
  if (types.indexOf(type) > -1) {
    return true
  }
  return false
}
